package com.xdtech.wx.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.common.utils.JsonUtil;
import com.xdtech.sys.util.SysConstants;
import com.xdtech.web.controller.BaseController;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.wx.model.WxCompany;
import com.xdtech.wx.model.WxUserInfo;
import com.xdtech.wx.service.WxCompanyService;
import com.xdtech.wx.service.WxPzswQuestionService;
import com.xdtech.wx.service.WxUserInfoService;
import com.xdtech.wx.util.SNSUserInfo;
import com.xdtech.wx.util.WeixinOauth2Token;
import com.xdtech.wx.util.WeixinUtil2;
import com.xdtech.wx.vo.PzswSolveVo;
import com.xdtech.wx.vo.PzswVo;
import com.xdtech.wx.vo.WxUserInfoItem;
@Controller
//@Scope("session")
@Scope("prototype")
public class PzswController extends BaseController{
    
	List<PzswSolveVo> pzswSolveVos = new ArrayList<PzswSolveVo>();
	@Autowired
	private WxPzswQuestionService wxPzswQuestionService;
	@RequestMapping(value="/pzsw2.action",params = "page")
	public ModelAndView page2(HttpServletRequest request,String page) {
		return new ModelAndView("wx/pzsw2/"+page+"_ftl");
	}
	
	@RequestMapping(value="/pzsw.action",params = "share")
	public ModelAndView share(HttpServletRequest request) {
		getWxConfigSign(request);
		return new ModelAndView("wx/pzsw/share_ftl");
	}

	protected void getWxConfigSign(HttpServletRequest request) {
		Map<String,Object>  ret = new HashMap<String,Object> ();
        ret= WeixinUtil2.getWxConfig(request);
        request.setAttribute("appId", ret.get("appId"));
        request.setAttribute("timestamp", ret.get("timestamp"));
        request.setAttribute("nonceStr", ret.get("nonceStr"));
        request.setAttribute("signature", ret.get("signature"));
	}
	
	@RequestMapping(value="/pzsw.action",params = "page")
	public ModelAndView page(HttpServletRequest request,String page) {
		getWxConfigSign(request);
		Object obj = getPzswQuestion(request);
		log.info(request.getSession().getId());
		if (StringUtils.isBlank(page)||obj==null) {
			page = "index4";
		}
		
		if ("index4".equals(page)) {
			PzswVo pzswVo = getPzswQuestion(request);
			if (pzswVo==null) {
				pzswVo = new PzswVo();
			}
			request.getSession().setAttribute("pzsw",pzswVo);
			return new ModelAndView("wx/pzsw/"+page+"_ftl");
		}
		
		//非后退
		if (!"1".equals(request.getParameter("back"))) {
			PzswVo pzswVo = getPzswQuestion(request);
			if ("index5".equals(page)) {
				pzswVo.setName(request.getParameter("name"));
				pzswVo.setDept(request.getParameter("dept"));
			}
			
			if ("index51".equals(page)||"index53".equals(page)) {
				//重新选择问卷模型 ，清除之前填写信息
				if (!request.getParameter("moduleType").equals(pzswVo.getModuleType())) {
					PzswVo pzswVoTemp = new PzswVo(pzswVo.getName(),pzswVo.getDept(),request.getParameter("moduleType"));
					pzswVo = pzswVoTemp;
				}
				
			}
			
			//填写问题1内容
			if ("content1-2".equals(page)||"content2-2".equals(page)) {
				pzswVo.setQuestionName(request.getParameter("questionName"));
			}
			//填写问题原因，有三个
			if ("content1-3-1".equals(page)||"content2-3-1".equals(page)) {
				pzswVo.setQuestionReason1(request.getParameter("questionReason1"));
				pzswVo.setQuestionReason2(request.getParameter("questionReason2"));
				pzswVo.setQuestionReason3(request.getParameter("questionReason3"));
			}
			
			//记录原因
			if ("content1-4".equals(page)||"content2-4".equals(page)) {
				pzswVo.getReason1Solve1().setName(request.getParameter("reason1Solve1"));
				pzswVo.getReason1Solve2().setName(request.getParameter("reason1Solve2"));
				pzswVo.getReason2Solve1().setName(request.getParameter("reason2Solve1"));
				pzswVo.getReason2Solve2().setName(request.getParameter("reason2Solve2"));
				pzswVo.getReason3Solve1().setName(request.getParameter("reason3Solve1"));
				pzswVo.getReason3Solve2().setName(request.getParameter("reason3Solve2"));
			}
			//回显已经选择最佳解决方案
			if ("content1-5".equals(page)||"content2-5".equals(page)) {
//				List<PzswSolveVo> selectList = getSelectPzsw(pzswVo);
				
			}
			if ("upload".equals(page)) {
//				request.getSession()
			}
			request.getSession().setAttribute("pzsw", pzswVo);
		}
		
		
		return new ModelAndView("wx/pzsw/"+page+"_ftl");
	}

	private PzswVo getPzswQuestion(HttpServletRequest request) {
		return (PzswVo) (request.getSession().getAttribute("pzsw"));
	}
	
	@RequestMapping(value="/pzsw.action",params = "submit")
	@ResponseBody
	public ResultMessage submit(HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
		pzswSolveVos.clear();
		String reason1Solve1 = request.getParameter("reason1Solve1");
		String reason1Solve2 = request.getParameter("reason1Solve2");
		String reason2Solve1 = request.getParameter("reason2Solve1");
		String reason2Solve2 = request.getParameter("reason2Solve2");
		String reason3Solve1 = request.getParameter("reason3Solve1");
		String reason3Solve2 = request.getParameter("reason3Solve2");
		PzswVo pzswVo = getPzswQuestion(request);
		if ("true".equals(reason1Solve1)) {
			pzswSolveVos.add(pzswVo.getReason1Solve1());
		}
		pzswVo.getReason1Solve1().setChoose(reason1Solve1);
		
		if ("true".equals(reason1Solve2)) {
			pzswSolveVos.add(pzswVo.getReason1Solve2());
		}
		pzswVo.getReason1Solve2().setChoose(reason1Solve2);
		
		if ("true".equals(reason2Solve1)) {
			pzswSolveVos.add(pzswVo.getReason2Solve1());
		}
		pzswVo.getReason2Solve1().setChoose(reason2Solve1);
		
		if ("true".equals(reason2Solve2)) {
			pzswSolveVos.add(pzswVo.getReason2Solve2());
		}
		pzswVo.getReason2Solve2().setChoose(reason2Solve2);
		if ("true".equals(reason3Solve1)) {
			pzswSolveVos.add(pzswVo.getReason3Solve1());
		}
		pzswVo.getReason3Solve1().setChoose(reason3Solve1);
		if ("true".equals(reason3Solve2)) {
			pzswSolveVos.add(pzswVo.getReason3Solve2());
		}
		pzswVo.getReason3Solve2().setChoose(reason3Solve2);
		request.getSession().setAttribute("pzswSolveVos", pzswSolveVos);
		Long id = wxPzswQuestionService.saveSubmitInfo(pzswVo);
		pzswVo.setId(id);
		
		request.getSession().setAttribute("pzsw", pzswVo);
		return r;
	}
	
	@RequestMapping(value="/pzsw.action",params = "getWxConfig")
	@ResponseBody
	public ResultMessage getWxConfig(HttpServletRequest request,String url) {
		ResultMessage r = new ResultMessage();
		Map<String, Object> maps = WeixinUtil2.getSign(url);
		r.setObj(maps);
		return r;
		
	}

//	private List<PzswSolveVo> getSelectPzsw(PzswVo pzswVo2) {
//		
//		return pzswSolveVos;
//	}
	
	
	@ResponseBody
	@RequestMapping(value = "pzsw.action",params = "upload")
	public String uploadFile(HttpServletRequest request,
			@RequestParam("filedata") MultipartFile file) throws Exception {
		List<String> filePathList = new ArrayList<String>();
		ResultMessage rs = new ResultMessage();
		try {
			String rootUrl = ApplicationContextUtil.getWebappUrl();
			String filePath = "pzswUploadFile/"+DateUtil.dateToString(new Date(), DateStyle.YYYYMMDD);
			String uploadDir = request.getRealPath("/"+filePath);
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			int indexFile = file.getOriginalFilename().lastIndexOf(".");
			String fileName = System.currentTimeMillis()+"_"+RandomStringUtils.random(4, "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")+file.getOriginalFilename().substring(indexFile, file.getOriginalFilename().length());
//			System.out.println(file.getContentType());
			String imgUrl = filePath+"/"+fileName;
			filePath = uploadDir + "/"+fileName;
			file.transferTo(new File(filePath));
//			filePathList.add(imgUrl);
			rs.setObj(imgUrl);
			String pzswId = request.getParameter("pzswId");
			if (StringUtils.isNotBlank(pzswId)) {
				wxPzswQuestionService.saveImgUrl(pzswId!=null?Long.valueOf(pzswId):null,imgUrl);
			}

		} catch (IOException e) {
			log.error("upload error",e);
		}
		return JsonUtil.getJsonStr(rs);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
//	@ResponseBody
//	@RequestMapping(value = "pzsw.action",params = "upload")
//	public ResultMessage upload(HttpServletRequest req,String pzswId,HttpServletResponse res) throws Exception {
//		List<String> filePathList = new ArrayList<String>();
//		ResultMessage rs = new ResultMessage();
//		res.setContentType("text/html;charset=UTF-8");
//
//	    // Create path components to save the file
//	    final Part filePart = req.getPart("filedata");
//	    final String fileName = getFileName(filePart);
//
//	    OutputStream out = null;
//	    InputStream filecontent = null;
//	    final PrintWriter writer = res.getWriter();
//	    
//		try {
//			String rootUrl = ApplicationContextUtil.getWebappUrl();
//			String filePath = "uploadFile/"+DateUtil.dateToString(new Date(), DateStyle.YYYYMMDD);
//			String uploadDir = req.getRealPath("/"+filePath);
//			File dirPath = new File(uploadDir);
//			if (!dirPath.exists()) {
//				dirPath.mkdirs();
//			}
//			String imgUrl = filePath+"/"+fileName;
//			filePath = uploadDir + "/"+fileName;
////			file.transferTo(new File(filePath));
//			
//			
//			out = new FileOutputStream(new File(filePath));
//	        filecontent = filePart.getInputStream();
//
//	        int read = 0;
//	        final byte[] bytes = new byte[1024];
//
//	        while ((read = filecontent.read(bytes)) != -1) {
//	            out.write(bytes, 0, read);
//	        }
//	        writer.println("New file " + fileName + " created at " + uploadDir);
//	        rs.setObj(imgUrl);
////	        WxPzswQuestionService wxPzswQuestionService2 = ApplicationContextUtil.getContext().getBean(WxPzswQuestionService.class);
//			wxPzswQuestionService.saveImgUrl(pzswId!=null?Long.valueOf(pzswId):null,imgUrl);
//		} catch (Exception e) {
//			e.printStackTrace();
//			rs.setFailMsg("上传处理失败");
//		} finally {
//	        if (out != null) {
//	            out.close();
//	        }
//	        if (filecontent != null) {
//	            filecontent.close();
//	        }
//	        if (writer != null) {
//	            writer.close();
//	        }
//	    }
//		return rs;
//	}
//	
//	private String getFileName(final Part part) {
//	    final String partHeader = part.getHeader("content-disposition");
//	    for (String content : part.getHeader("content-disposition").split(";")) {
//	        if (content.trim().startsWith("filename")) {
//	            return content.substring(
//	                    content.indexOf('=') + 1).trim().replace("\"", "");
//	        }
//	    }
//	    return null;
//	}
	
	@RequestMapping(value="/wxShare.action")
	public ModelAndView shareTest(HttpServletRequest request) {
		getWxConfigSign(request);
		// 用户同意授权后，能获取到code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        
        // 用户同意授权
        if (!"authdeny".equals(code)&&StringUtils.isNotBlank(code)) {
        	 String appId = "wx44fdc31fc571757d"; // 必填，公众号的唯一标识
             String secret = "9cb6776d0305735194574d2118df7df3";
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = WeixinUtil2.getOauth2AccessToken(appId, secret, code);
            if (weixinOauth2Token!=null) {
            	// 网页授权接口访问凭证
                String accessToken = weixinOauth2Token.getAccessToken();
                // 用户标识
                String openId = weixinOauth2Token.getOpenId();
                // 获取用户信息
                SNSUserInfo snsUserInfo = WeixinUtil2.getSNSUserInfo(accessToken, openId);

                // 设置要传递的参数
                request.setAttribute("user", snsUserInfo);
                request.setAttribute("state", state);
//                WxUserInfoItem userInfoItem = wxUserInfoService.getUserInfoByOpenId(openId);
//                if (userInfoItem!=null&&SysConstants.YES.equals(userInfoItem.getSignStatus())) {
//                	request.setAttribute("userInfo", userInfoItem);
//            		return new ModelAndView("wx/led/result_ftl");
//				}
            }
            
        }
        request.setAttribute("companyCode", request.getParameter("companyCode"));
        
		return new ModelAndView("wx/pzsw/share_ftl");
	}
	@Autowired
	private WxCompanyService wxCompanyService;
	@RequestMapping(value="/wxLed.action")
	public ModelAndView wxLed(HttpServletRequest request,String companyCode) {
		request.setAttribute("count", wxCompanyService.getPersonCount(companyCode));
		request.setAttribute("signCount", wxUserInfoService.getSignPersonCount(companyCode));
		return new ModelAndView("wx/led/index_ftl");
	}
	
	static Map<String, List<WxUserInfoItem>> wxMap = new ConcurrentHashMap();
	static Map<String, Long> timeMap = new ConcurrentHashMap<String, Long>();
	
	@Autowired
	private WxUserInfoService wxUserInfoService;
	
	@RequestMapping(value="/signWxUserInfo.action")
	@ResponseBody
	public ResultMessage signWxUserInfo(WxUserInfoItem userInfo) {
		ResultMessage r = new ResultMessage();
//		if(StringUtils.isBlank(userInfo.getOpenId())) {
//			r.setFailMsg("请在微信中扫描打开");
//			return r;
//		}
		if (StringUtils.isBlank(userInfo.getName())) {
			r.setFailMsg("姓名为空，请填写完整");
			return r;
		}
		WxUserInfo wxUserInfo = wxUserInfoService.getWxUserByName(userInfo.getName());
		if(wxUserInfo==null) {
			r.setFailMsg("查无受邀信息，请核对姓名信息");
			return r;
		}
		wxUserInfo.setOpenId(userInfo.getOpenId());
		wxUserInfo.setNickName(userInfo.getNickName());
		wxUserInfo.setCountry(userInfo.getCountry());
		wxUserInfo.setProvince(userInfo.getProvince());
		wxUserInfo.setCity(userInfo.getCity());
		wxUserInfo.setHeadImgUrl(userInfo.getHeadImgUrl());
		wxUserInfo.setPosition(userInfo.getPosition());
		wxUserInfo.setSex(userInfo.getSex());
		WxCompany wxCompany = wxCompanyService.getCompanyByCode(userInfo.getCompanyCode());
		if (wxCompany!=null) {
			wxUserInfo.setCompany(wxCompany.getName());
		}
		wxUserInfo.setWxCompany(wxCompany);
		if (SysConstants.YES.equals(wxUserInfo.getSignStatus())) {
			//已签到过
			userInfo.setFlag("1");
		} else {
			//首次扫描签到
			wxUserInfo.setSignStatus(SysConstants.YES);
			userInfo.setFlag("0");
		}
		wxUserInfoService.save(wxUserInfo);
		addToMonitorMap(userInfo);
		r.setObj(userInfo);
		r.setMsg("签到成功");
		return r;
		
	}
	

	@RequestMapping(value="/signWxUserInfo2.action")
	public ModelAndView signWxUserInfo2(HttpServletRequest request,WxUserInfoItem userInfo) {
		ResultMessage rmMessage = signWxUserInfo(userInfo);
		if (rmMessage.isSuccess()) {
			request.setAttribute("userInfo", wxUserInfoService.getWxUserByName(userInfo.getName()));
		} 
		request.setAttribute("rs", rmMessage);
		return new ModelAndView("wx/led/result_ftl");
	}
	
	private void addToMonitorMap(WxUserInfoItem userInfo) {
		Set<String> clientIds = wxMap.keySet();
		for (String key : clientIds) {
			wxMap.get(key).add(userInfo);
			//如果超过1分钟移除
			if (timeMap.containsKey(key)) {
				if (System.currentTimeMillis()-timeMap.get(key)>60*1000) {
					wxMap.remove(key);
					timeMap.remove(key);
				}
			}
			
		}
	}

	@RequestMapping(value="/getWxSignInfo.action")
	@ResponseBody
	public ResultMessage getWxSignInfo(HttpServletRequest request,String timestamp) {
		//获取签到信息
		ResultMessage rm = new ResultMessage();
		if (StringUtils.isNotBlank(timestamp)) {
			if (wxMap.containsKey(timestamp)) {
				List<WxUserInfoItem> items = new ArrayList<WxUserInfoItem>();
				items.addAll(wxMap.get(timestamp));
				rm.setObj(items);
				wxMap.get(timestamp).clear();
			} else {
				wxMap.put(timestamp, new ArrayList<WxUserInfoItem>());
			}
			timeMap.put(timestamp, System.currentTimeMillis());
		}
		return rm;
	}
	@RequestMapping(value = "rd.action")
	public ModelAndView rd(String companyCode,HttpServletRequest request) throws Exception {
		String backurl = request.getScheme() + "://www.jmax4you.com/jmax/wxShare.action?companyCode=" +companyCode;
		String url = getWebWxAuthorizeUrl("wx44fdc31fc571757d", backurl);
//		return "redirect:" + backurl;
//		backurl = "http://localhost:8090/jmax/wxShare.action?companyCode=max";
		return new ModelAndView("redirect:"+url); 

	}
	
	@RequestMapping(value = "signResult.action")
	public ModelAndView signResult(HttpServletRequest request,String openId,String name) throws Exception {
		request.setAttribute("userInfo", wxUserInfoService.getWxUserByName(name));
		return new ModelAndView("wx/led/result_ftl");

	}

	
	public static String getWebWxAuthorizeUrl(String appid, String url) throws Exception{
		String WEB_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; 
		return String.format(WEB_OAUTH_URL, appid,url);
	}
	
}
